$(document).ready(function(){
	var url = window.location.href;
	$.ajax( {
		type : "GET",
		contentType:"application/json",
		dataType : 'json',
		url: "surroundingIbeacon",
		data: { url: url},
		async: true,
		success : function(ret) {
			var appid = ret.appid;
			var timestamp=ret.timestamp;
			var nonceStr=ret.nonceStr;
			var signature = ret.signature;
			wx.config({
			  debug: false,
			  appId: appid,// 必填，公众号的唯一标识
			  timestamp: timestamp,// 必填，生成签名的时间戳
			  nonceStr: nonceStr,// 必填，生成签名的随机串
			  signature: signature,// 必填，签名
			  jsApiList: [
			    'checkJsApi',
				'startSearchBeacons',
				'stopSearchBeacons',
				'onSearchBeacons'
			  ]
			});
			wx.ready(function () {
			  	jstartSearchBeacons();//开始开启
			});
			wx.error(function (res) {
				  alert(res.errMsg);
				});	
		}
	})
})

function jstartSearchBeacons(){
  	console.log("开始开启")
	wx.startSearchBeacons({
   	ticket:"",
   	complete:function(res){
		 console.log(JSON.stringify(res));
		 var status = res.errMsg;
		 var message = "";
		 if(status=="startSearchBeacons:ok"){
			 message = "打开成功";
			 jonSearchBeacons()
		 }else if(status=="startSearchBeacons:already started"){
			 message = "";//上次未正常关闭
			 jstopSearchBeacons();
		 }else if(status=="startSearchBeacons:bluetooth power off"){
			 message = "蓝牙未打开";
		 }else if(status=="startSearchBeacons:location service disable"){
			 message = "地理位置服务未打开";
		 }else if(status=="startSearchBeacons:system unsupported"){
			 message = "系统不支持";
		 }
		 $("#message").html(message)
  	 }
	});
}
function jonSearchBeacons(){
	console.log("查询周边设备")
	wx.onSearchBeacons({
		complete: function(argv){
			console.log("查询成功")
			console.log(argv)
			var onSearchBeaconsstatus = argv.errMsg;
			if (onSearchBeaconsstatus == "onSearchBeacons:ok") {
				jstopSearchBeacons();
				var beacons = argv.beacons
				var arg = JSON.stringify(argv);
				if(beacons.length!=0){
					//ajax请求
					$.ajax({
						type: "GET",
						contentType: "application/json",
						dataType: 'json',
						url: "getsurroundingSite",
						data: {
							arg: arg
						},
						async: true,
						success: function(ret){
						
						
						}
					})
				}
			}
		}
	})
}
function jstopSearchBeacons(){
	console.log("开始关闭")
	  	wx.stopSearchBeacons({
	  	   complete:function(res){
	  		 if(res.errMsg=="stopSearchBeacons:ok"){
	  			$("#message").html("关闭成功")
	  		 }else{
	  			$("#message").html("关闭失败")
	  		 }
	  	   //回调函数
	  	   }
	  	});
}
